package cn.org.xuanguang.kepler.hormos.orm.acl.impl;

import cn.org.xuanguang.kepler.hormos.orm.acl.AbstractIPolicy;
import cn.org.xuanguang.kepler.hormos.orm.acl.IPolicy;
import cn.org.xuanguang.kepler.hormos.orm.acl.PolicyCondition;
import cn.org.xuanguang.kepler.hormos.rdb.dml.operator.AbstractOperatorParameter;
import cn.org.xuanguang.kepler.hormos.rdb.dml.operator.insert.InsertOperatorParameter;
import cn.org.xuanguang.kepler.hormos.rdb.dsl.param.Term;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 多租户支持
 */
public class TenantPolicy extends AbstractIPolicy {

    private static final Logger log = LoggerFactory.getLogger(TenantPolicy.class);
    // 查找默认租户类型和租户id，保存到租户缓存中
    @Getter
    @Setter
    private String tenantId;


    @Override
    public String getPolicyName() {
        return "多租户";
    }

    @Override
    public String getPolicyValue() {
        return "MultiTenants";
    }

    @Override
    public String getPolicyType() {
        return IPolicy.TENANT;
    }

    @Override
    public String getPolicyDesc() {
        return "多租户支持，提供对实例级别、字段级别的支持";
    }

    @Override
    public String getPolicyCode() {
        return IPolicy.TENANT;
    }

    @Override
    public String getPolicyGroup() {
        return "";
    }

    @Override
    public String getPolicyGroupDesc() {
        return "";
    }

    @Override
    public String getPolicyGroupCode() {
        return "";
    }


    @Override
    public PolicyCondition[] getPolicyCondition() {
        return policyConditions.toArray(PolicyCondition[]::new);
    }

    // 此处添加 租户id
    @Override
    public void before(AbstractOperatorParameter target) {
        // 租户查询条件
        List<Term> terms = target.getTerms();
        for (PolicyCondition policyCondition : getPolicyCondition()) {
            Term term = new Term();
            term.setColumn(policyCondition.getColumn());
            term.setTermType(policyCondition.getType());
            term.setValue(policyCondition.getValue());
            terms.add(term);
            // 租户id及插入条件
            // 判断是否存在租户的字段
            String tenantColumn = policyCondition.getColumn();
            Object tenantId = policyCondition.getValue();
            //判断AbstractOperatorParameter的列里是否有该字段
            if (target instanceof InsertOperatorParameter){
                // 添加租户字段及数值
                ((InsertOperatorParameter) target).getColumns().add(tenantColumn);
                ((InsertOperatorParameter) target).getValues().add(tenantId);
            }
        }
        target.setTerms(terms);


    }

    @Override
    public void after() {
        log.debug("完成租户id的包装");
    }
}
